import os
import yaml
from pathlib import Path

class 配置管理:
    """统一管理所有模块的配置"""
    
    def __init__(self):
        self.配置路径 = self._获取配置路径()
        self.配置数据 = self._加载配置()
    
    def _获取配置路径(self):
        """确定配置文件路径"""
        可能路径 = [
            "/root/workspace/wenyan-plus-plus/we/GITEE_PARAMS",
            str(Path.home() / ".wenyan_plus_plus" / "config.yml"),
            str(Path.cwd() / "config" / "default.yml"),
            str(Path.cwd() / ".gitee" / "config.yml")
        ]
        
        for 路径 in 可能路径:
            if os.path.exists(路径):
                return 路径
        
        # 如果都不存在，创建默认配置
        默认路径 = 可能路径[1]
        os.makedirs(os.path.dirname(默认路径), exist_ok=True)
        self._创建默认配置(默认路径)
        return 默认路径
    
    def _创建默认配置(self, 路径):
        """创建默认配置文件"""
        默认配置 = {
            "gitee": {
                "access_token": os.getenv("GITEE_ACCESS_TOKEN", ""),
                "api_endpoint": "https://gitee.com/api/v5",
                "api_version": "v5"
            },
            "repository": {
                "owner": os.getenv("GITEE_REPO_OWNER", ""),
                "name": os.getenv("GITEE_REPO_NAME", ""),
                "branch": "main"
            },
            "modules": {
                "rhythm": {"enabled": True, "priority": 1},
                "quantum": {"enabled": True, "priority": 2},
                "poetry": {"enabled": False, "priority": 3},
                "culture": {"enabled": False, "priority": 4},
                "semantics": {"enabled": False, "priority": 5},
                "taichi": {"enabled": False, "priority": 6},
                "ml": {"enabled": False, "priority": 7}
            },
            "logging": {
                "level": "INFO",
                "file": "/var/log/wenyan-plus-plus/app.log"
            }
        }
        
        with open(路径, 'w', encoding='utf-8') as f:
            yaml.dump(默认配置, f, allow_unicode=True)
        print(f"已创建默认配置文件: {路径}")
    
    def _加载配置(self):
        """加载配置文件"""
        try:
            with open(self.配置路径, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f) or {}
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            return {}
    
    def 获取模块配置(self, 模块名):
        """获取特定模块的配置"""
        return self.配置数据.get("modules", {}).get(模块名, {})
    
    def 更新配置(self, 新配置):
        """更新配置并保存"""
        self.配置数据.update(新配置)
        with open(self.配置路径, 'w', encoding='utf-8') as f:
            yaml.dump(self.配置数据, f, allow_unicode=True)
